//
// Created by 24087 on 2025/3/29.
//

#include "../Inc/my_app.h"

void LED_Init()
{
    const uint16_t led = LED1_Pin | LED2_Pin | LED3_Pin | LED4_Pin;
    HAL_GPIO_WritePin(LED1_GPIO_Port, led, SET);
}


/*赋值*/
KeyState key1_state = KEY_IDLE;
KeyState key2_state = KEY_IDLE;
uint32_t last_tick = 0;

uint8_t Get_KeyValue(void)
{
    static uint8_t counter = 0;

    // 检测KEY1
    if (HAL_GPIO_ReadPin(Key1_GPIO_Port, Key1_Pin) == GPIO_PIN_RESET)
    {
        const uint32_t debounce_delay = 10;
        switch (key1_state)
        {
            case KEY_IDLE:
                key1_state = KEY_DEBOUNCE;
                last_tick = HAL_GetTick();
                break;
            case KEY_DEBOUNCE:
                if (HAL_GetTick() - last_tick > debounce_delay)
                {
                    key1_state = KEY_PRESSED;
                    counter = (counter + 1) % 7; // 循环0-6
                    TxData[0] = counter;
                    CAN_Send(Tx_header, TxData, MailBox0);
                }
                break;
            case KEY_PRESSED:
                // 保持状态直到按键释放
                break;
        }
    } else
    {
        key1_state = KEY_IDLE;
    }

    return counter;
}

// 全局变量记录当前LED状态
static uint16_t current_leds = 0;

void Update_LEDs(const uint8_t level)
{
    // 先关闭所有LED
    HAL_GPIO_WritePin(LED1_GPIO_Port,
                      LED1_Pin | LED2_Pin | LED3_Pin | LED4_Pin | LED5_Pin | LED6_Pin,
                      GPIO_PIN_SET);

    // 按等级点亮LED
    switch (level)
    {
        case 1:
            current_leds = LED1_Pin;
            break;
        case 2:
            current_leds = LED1_Pin | LED2_Pin;
            break;
        case 3:
            current_leds = LED1_Pin | LED2_Pin | LED3_Pin;
            break;
        case 4:
            current_leds = LED1_Pin | LED2_Pin | LED3_Pin | LED4_Pin;
            break;
        case 5:
            current_leds = LED1_Pin | LED2_Pin | LED3_Pin | LED4_Pin | LED5_Pin;
            break;
        case 6:
            current_leds = LED1_Pin | LED2_Pin | LED3_Pin | LED4_Pin | LED5_Pin | LED6_Pin;
            break;
        default:
            current_leds = 0;
            break;
    }

    // 应用新状态
    HAL_GPIO_WritePin(LED1_GPIO_Port, current_leds, GPIO_PIN_RESET);
}
